<template>
  <div ref="chartRef" :class="className" :style="{height:height,width:width}" />
</template>

<script setup lang="ts">
import * as echarts from 'echarts'
import { debounce } from '@/utils'
import { onMounted, onBeforeUnmount, ref, nextTick } from 'vue'

const props = defineProps({
  className: {
    type: String,
    default: 'chart'
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '300px'
  }
})

const chartRef = ref<HTMLElement | null>(null)
const chart = ref<echarts.ECharts | null>(null)

const initChart = async () => {
  await nextTick()
  if (!chartRef.value) return
  
  if (!chart.value) {
    chart.value = echarts.init(chartRef.value)
  }

  chart.value.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎']
    },
    series: [
      {
        name: '访问来源',
        type: 'pie',
        radius: '55%',
        center: ['50%', '60%'],
        data: [
          { value: 335, name: '直接访问' },
          { value: 310, name: '邮件营销' },
          { value: 234, name: '联盟广告' },
          { value: 135, name: '视频广告' },
          { value: 1548, name: '搜索引擎' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  })
}

const __resizeHandler = debounce(() => {
  if (chart.value) {
    chart.value.resize()
  }
}, 100) as EventListener

onMounted(() => {
  initChart()
  window.addEventListener('resize', __resizeHandler)
})

onBeforeUnmount(() => {
  if (!chart.value) {
    return
  }
  window.removeEventListener('resize', __resizeHandler)
  chart.value.dispose()
  chart.value = null
})
</script>
